package com.lanou.bookstore.category.dao;

import com.lanou.bookstore.book.domain.Book;
import com.lanou.bookstore.category.domain.Category;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CategoryDaoImpl implements CategoryDao {
    // c3p0初始化
    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

    @Override
    public List<Category> queryAll() {

        try {
            Connection conn = dataSource.getConnection();

            QueryRunner qr = new QueryRunner();
            List<Category> clist = qr.query(conn,
                    "select * from category",
                    new BeanListHandler<Category>(Category.class));

            DbUtils.close(conn);
            return clist;

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return new ArrayList<Category>();
    }

    @Override
    public void addCategory(Category cate) {

        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            int result = qr.update(conn, "insert into category (cid, cname) values(?,?)",
                    cate.getCid(),cate.getCname());
            DbUtils.close(conn);

        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void delete(String cate) {
        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            int result = qr.update(conn, "delete from category where cname=?",
                    cate);

            DbUtils.close(conn);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void modCat(String cate, String input) {
        try {
            Connection conn = dataSource.getConnection();

            // 使用dbutils添加数据
            QueryRunner qr = new QueryRunner();
            int result = qr.update(conn, "update category set cname = ? where cname =?",
                    input,cate);

            DbUtils.close(conn);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


}
